package cn.mrcode.fd.blog.task;

import cn.mrcode.fd.blog.buutil.BeanUtil;
import cn.mrcode.fd.blog.entity.SysConfig;
import cn.mrcode.fd.blog.services.ISysConfigService;
import cn.mrcode.fd.utils.log.track.LogTrackTemplateUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * 缓存自动扫描刷新任务类
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2016/1/27 21:49
 */
public class CacheAutoScanTask implements Runnable{
    private static Logger LOGGER = LoggerFactory.getLogger(CacheAutoScanTask.class);
    private static String apiName = "[缓存自动扫描刷新task]";

    private static ISysConfigService iSysConfigService = BeanUtil.beans.getBean(ISysConfigService.class);
    private static ConcurrentHashMap<String,LinkedHashMap<String,SysConfig>> cacheMap = new ConcurrentHashMap<>();
    private static long autoScanTime = 0;  //自动扫描时间间隔,为0则不扫描

    /**
     * 刷新系统配置表缓存数据到程序中
     */
    public static void refresh(){
        LOGGER.info(LogTrackTemplateUtil.svMsg(apiName,"开始刷新系统缓存"));
        List<SysConfig>  list = iSysConfigService.findAll();
        //缓存map
        ConcurrentHashMap<String,LinkedHashMap<String,SysConfig>> tempCacheMap = new ConcurrentHashMap<>();

        if(CollectionUtils.isNotEmpty(list)){
            for (SysConfig sysConfig : list) {
                String group = sysConfig.getSgroup();
                String key = sysConfig.getSkey();
                if(tempCacheMap.containsKey(group)){
                    LinkedHashMap<String, SysConfig> value = tempCacheMap.get(group);
                    value.put(key,sysConfig);
                }else{
                    LinkedHashMap<String, SysConfig> value = new LinkedHashMap<>();
                    value.put(key,sysConfig);
                    tempCacheMap.put(group, value);
                }
            }
            cacheMap.clear();
            cacheMap.putAll(tempCacheMap);
            String cache_isrefresh = getValue("config", "cache_isrefresh");
            if(StringUtils.isNotBlank(cache_isrefresh) && !cache_isrefresh.equals("0")){
                String cache_auto_scan_time = getValue("config", "cache_auto_scan_time");
                if(StringUtils.isNotBlank(cache_auto_scan_time)) {
                    autoScanTime = Long.parseLong(cache_auto_scan_time);
                    LOGGER.info(LogTrackTemplateUtil.svMsg(apiName,"自动刷新缓存配置生效，刷新时间间隔=%s 毫秒",autoScanTime+""));
                }
            }else{
                autoScanTime = 0;
                LOGGER.info(LogTrackTemplateUtil.svMsg(apiName,"不自动刷新缓存配置生效"));
            }
        }
        LOGGER.info(LogTrackTemplateUtil.svMsg(apiName,"刷新系统缓存结束"));
    }

    /**
     * 获取一个配置值
     * @param group 组名称
     * @param key 值的key
     * @return 没有则返回null
     */
    public static String getValue(String group,String key){
        if(cacheMap.containsKey(group)){
            LinkedHashMap<String, SysConfig> valueMap = cacheMap.get(group);
            if(valueMap.containsKey(key)){
                return valueMap.get(key).getSvalue();
            }
        }
        return null;
    }

    /**
     * 获取一组值
     * @param group 组名称
     * @return 没有则返回null
     */
    public static LinkedHashMap<String,String> getGroup(String group){
        if(cacheMap.containsKey(group)){
            LinkedHashMap<String, SysConfig> valueMap = cacheMap.get(group);
            LinkedHashMap<String,String> groupMap = new LinkedHashMap<>();
            for(Map.Entry<String,SysConfig> ent : valueMap.entrySet()){
                groupMap.put(ent.getKey(),ent.getValue().getSvalue());
            }
            return groupMap;
        }
        return null;
    }

    @Override
    public void run() {
        if(autoScanTime != 0){
            LOGGER.info(LogTrackTemplateUtil.svMsg(apiName,"自动刷新缓存task巡查开始"));
            try {
                TimeUnit.MILLISECONDS.sleep(autoScanTime);
                refresh();
            } catch (InterruptedException e) {
                LOGGER.info(LogTrackTemplateUtil.svMsg(apiName,"线程休眠被中断,info=%s,本地化信息=%s",e.getMessage(),e.getLocalizedMessage()));
                e.printStackTrace();
            }
        }
    }
}
